<?php

require_once("config.php");

/*
Uncomment for basic password protection
session_start();
if ($_SESSION['password'] != $password) {

	if ($_REQUEST['action'] == "login" && $_REQUEST['password'] == $password) {
		$_SESSION['password'] = $_REQUEST['password'];
	} else {
		$fp = fopen("login.html", "rb");
		if (!$fp) die("ERROR: Unable to open file. template.html");
		$data = fread($fp, filesize("template.html"));
		fclose($fp);
		echo $data;
		exit;
	}
}
*/
switch ($_REQUEST['action']) {
	case "addContact":
		addContact($_REQUEST['charactername'], $_REQUEST['group']);
		break;
	case "delContact":
		delContact($_REQUEST['id']);
		break;
	default:
		showContacts($_REQUEST['search'], $_REQUEST['orderby'], $_REQUEST['page']);
}


function showContacts($search = '', $orderby = 'group', $page = 1) {
	global $dbfile,$groups,$perpage;
	if (empty($search)) $search = '';
	if (empty($orderby)) $orderby = 'group';
	if (empty($page)) $page = 1;
	$fp = fopen($dbfile,'r'); 
	if (!$fp) die("ERROR: Unable to open file. ".$dbfile);
	$data = array();
	while (!feof($fp)) {
		$line = fgets($fp, 1024); //use 2048 if very long lines 
		list($thisID, $thisCharactername, $thisGroup) = split ('\|', $line);
		if (preg_match("/".$search."/i",$thisCharactername)) {
			array_push($data, array(
				'id'=>$thisID,
				'charactername'=>$thisCharactername,
				'group'=>$thisGroup
			));
		}
		$fp++;
	}
	fclose($fp); 

	if (!empty($data)) usort($data, $orderby."sort");

	$cnt = 0;
	$pagecnt = round((count($data)-1)/$perpage);
	//echo "pagecnt: ".$pagecnt."<BR/>\n";
	//echo "start: ".($page-1)*$perpage."<BR/>\n";
	//echo "end: ".($page)*$perpage."<BR/>\n";

	$contacts = "";
	$contacts .= "<TABLE BORDER=0 CELLPADDING=3 CELLSPACING=3>";	
	$contacts .= "<TR><TH COLSPAN=2>&nbsp;</TH><TH><A HREF='index.php?orderby=character'>Character</A></TH><TH><A HREF='index.php?orderby=group'>Group</A></TH></TR>";
	foreach ($data as $line) {
		if (!empty($line['charactername'])) {
			if ($cnt >= ($page-1)*$perpage) {
				$contacts .= "<TR><TD><button type='button' onclick='show(".$line['id'].")'>Show</button></TD><TD><button type='button' onclick='del(".$line['id'].",\"".$line['charactername']."\")'>Del</button></TD><TD>".$line['charactername']."</TD><TD>".$line['group']."</TD></TR>";
			}
			$cnt++;
			if ($cnt >= $page*$perpage) break;
		}
	}
	$contacts .= "</TABLE>";

	$cnt = 1;
	while ($pagecnt--) {
		if ($cnt == $page) {
			$contacts .= $cnt."&nbsp;&nbsp;";
		} else {
			$contacts .= "<A HREF='index.php?page=".$cnt."'>[".$cnt."]</A>&nbsp;&nbsp;";
		}
		$cnt++;
	}

	$dropdown = "<OPTION VALUE=''>--Select--</OPTION>";
	foreach ($groups as $group) {
		$dropdown .= "<OPTION>".$group."</OPTION>\n";
	}
	
	$fp = fopen("template.html", "rb");
	if (!$fp) die("ERROR: Unable to open file. template.html");
	$data = fread($fp, filesize("template.html"));
	fclose($fp);
	
	$data = str_replace("%contacts%", $contacts, $data);
	$data = str_replace("%groups%", $dropdown, $data);
	echo $data;
}


function addContact($charactername, $group) {
	global $dbfile,$groups,$perpage;
	if (!empty($charactername)) {

		// Check exists
		$fp = fopen($dbfile,'r'); 
		if (!$fp) die("ERROR: Unable to open file. ".$dbfile);
		$data = array();
		while (!feof($fp)) {
			$line = fgets($fp, 1024); //use 2048 if very long lines 
			list($thisID, $thisCharactername, $thisGroup) = split ('\|', $line);
			if ($charactername == $thisCharactername) error('Character already exists');	
			$fp++;
		}
		fclose($fp);

		// Find CharacterID
		$eve_api = "http://api.eve-online.com/eve/CharacterID.xml.aspx";
		$args = array("names"=>$charactername);

		$req = curl_init($eve_api);
		curl_setopt($req, CURLOPT_POST, true);
		curl_setopt($req, CURLOPT_POSTFIELDS, $args);
		curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
		$resp = curl_exec($req);
		$http_code = curl_getinfo($req,  CURLINFO_HTTP_CODE);
		curl_close($req);
		if ($http_code != 200 || strpos($resp, "<error") !== FALSE) {
			error("Error retrieving CharacterID");
		} else {
			if (preg_match("/name=\"".$charactername."\" characterID=\"([0-9]*)\"/i", $resp, $matches)) {
				$characterid = $matches[1];
			}
			if (!empty($characterid) && !empty($charactername)) {
				$fp = fopen ($dbfile, "a");
				if (!$fp) die("ERROR: Unable to open file. ".$dbfile);
				fwrite($fp,$characterid."|".$charactername."|".$group."\n");
				fclose ($fp);
			} else {
				error("Unable to retrieve CharacterID");
			}
		}
	}
	showContacts();
	echo "Added: ".$charactername." - ".$group."<BR/>\n";
}

function delContact($id) {
	
	// TODO: display confirm HTML form, or no confirm and smaller button
	
	global $dbfile,$groups,$perpage;
	$fp = fopen($dbfile,'r'); 
	if (!$fp) die("ERROR: Unable to open file. ".$dbfile);
	$data = array();
	while (!feof($fp)) {
		$line = fgets($fp, 1024); //use 2048 if very long lines 
		array_push($data, $line);
		$fp++;
	}
	fclose($fp);
	
	$fp = fopen ($dbfile, "w");
	if (!$fp) die("ERROR: Unable to open file. ".$dbfile);
	foreach ($data as $line) {
		$line = trim($line);
		if (empty($line)) continue;
		list($thisID, $thisCharactername, $thisGroup) = split ('\|', $line);
		if ($id != $thisID && !empty($thisID)) {
			if (!empty($thisCharactername)) fwrite($fp,$thisID."|".$thisCharactername."|".$thisGroup."\n");
		} else {
			$delChar = $thisCharactername;
			$delGroup = $thisGroup;
		}
	}
	fclose($fp);
	showContacts();
	echo "Deleted: ".$delChar." - ".$delGroup."<BR/>\n";
}

function error($e) {
	echo "<FONT COLOR='#ff3300'><STRONG>ERROR: ".$e."</STRONG></FONT><BR/>\n";
	showContacts();
	exit;
}



function groupsort($x, $y) {
	if ( $x['group'] == $y['group'] ) return 0;
	else if ( $x['group'] < $y['group'] ) return -1;
	else return 1;
}

function charactersort($x, $y) {
	if ( $x['charactername'] == $y['charactername'] ) return 0;
	else if ( $x['charactername'] < $y['charactername'] ) return -1;
	else return 1;
}


?>